﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Enyim.Caching;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace Heavysoft.Mince.Support
{
    public class CacheManager
    {
        static MemcachedClient client;
        static MD5 hasher = new MD5Cng();

        static MemcachedClient Client
        {
            get
            {
                if (CacheManager.client == null)
                {
                    Enyim.Caching.Configuration.MemcachedClientConfiguration config = new Enyim.Caching.Configuration.MemcachedClientConfiguration();
                    config.Servers.Add(new System.Net.IPEndPoint(IPAddress.Parse("192.168.0.12"), 11211));
                    config.Protocol = Enyim.Caching.Memcached.MemcachedProtocol.Text; //you must set a protocol
                    client = new Enyim.Caching.MemcachedClient(config);
                }
                return CacheManager.client;
            }
        }

        public static ulong IncrementId(string key)
        {
            //return Client.Increment(key, 1, 1, DateTime.MaxValue);
            return Client.Increment(key, 1, 1);
        }

        public static string MakeKey(string plainKey)
        {
            byte[] bs = Encoding.UTF8.GetBytes(plainKey);
            bs = CacheManager.hasher.ComputeHash(bs);
            return Encoding.UTF8.GetString(bs);
        }

        public static string MakeKey(string keyFormat, ulong id)
        {
            return MakeKey(string.Format(keyFormat, id.ToString()));
        }

        public static bool Add(string key, Object value)
        {
            return Client.Store(Enyim.Caching.Memcached.StoreMode.Add, key, value);
        }

        public static T Get<T>(string key)
        {
            return Client.Get<T>(key);
        }
    }
}